package com.cook.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.cook.dto.user.PostDTO;
import com.cook.entity.Posts;
import com.cook.service.PostsService;
import com.cook.mapper.PostsMapper;
import com.cook.vo.user.PostVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
* @author black-white spider
* @description 针对表【posts(用户动态表)】的数据库操作Service实现
* @createDate 2025-10-27 19:54:38
*/
@Service
@Slf4j
public class PostsServiceImpl extends ServiceImpl<PostsMapper, Posts> implements PostsService {

    @Autowired
    private PostsMapper postsMapper;

    /**
     * 分页查询用户动态
     * @param userId 用户ID
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return
     */
    public Map<String, Object> getPostsByUserIdWithPage(Long userId, Integer pageNum, Integer pageSize) {
        log.info("分页查询用户动态: userId={}, pageNum={}, pageSize={}", userId, pageNum, pageSize);

        try {
            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;

            // 查询数据
            List<PostVO> postList = postsMapper.selectPostsByUserIdWithPage(userId, offset, pageSize);
            int totalCount = postsMapper.selectPostsCountByUserId(userId);
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", postList);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);

            log.info("分页查询成功，共 {} 条数据，总页数: {}", postList.size(), totalPages);
            return result;

        } catch (Exception e) {
            log.error("分页查询用户动态失败: userId={}", userId, e);
            throw new RuntimeException("查询动态列表失败");
        }
    }

    /**
     * 分页查询所有动态
     * @param pageNum 页码
     * @param pageSize 每页数量
     * @return
     */
    public Map<String, Object> getAllPostsWithPage(Integer pageNum, Integer pageSize) {
        log.info("分页查询所有动态: pageNum={}, pageSize={}", pageNum, pageSize);

        try {
            // 计算偏移量
            int offset = (pageNum - 1) * pageSize;

            // 查询数据
            List<PostVO> postList = postsMapper.selectPostsWithPage(offset, pageSize);
            int totalCount = postsMapper.selectAllPostsCount();
            int totalPages = (int) Math.ceil((double) totalCount / pageSize);

            // 构建返回结果
            Map<String, Object> result = new HashMap<>();
            result.put("list", postList);
            result.put("pageNum", pageNum);
            result.put("pageSize", pageSize);
            result.put("totalCount", totalCount);
            result.put("totalPages", totalPages);
            result.put("hasNext", pageNum < totalPages);
            result.put("hasPrev", pageNum > 1);

            log.info("分页查询成功，共 {} 条数据，总页数: {}", postList.size(), totalPages);
            return result;

        } catch (Exception e) {
            log.error("分页查询用户动态失败: ", e);
            throw new RuntimeException("查询动态列表失败");
        }
    }

    /**
     * 创建动态
     * @param postDTO 动态DTO
     * @return
     */
    @Transactional
    public Long createPost(PostDTO postDTO) {
        log.info("创建动态: userId={}, contentLength={}",
                postDTO.getUserId(),
                postDTO.getContent() != null ? postDTO.getContent().length() : 0);

        try {
            // DTO 转 Entity
            Posts post = new Posts();
            BeanUtils.copyProperties(postDTO, post);

            // 插入数据库
            int result = postsMapper.insertPost(post);
            if (result > 0) {
                log.info("动态创建成功, ID: {}", post.getPostId());
                return post.getPostId();
            } else {
                throw new RuntimeException("创建动态失败");
            }
        } catch (Exception e) {
            log.error("创建动态失败: ", e);
            throw new RuntimeException("创建动态失败");
        }
    }

    /**
     * 删除动态
     * @param postId 动态ID
     * @param userId 用户ID
     * @return
     */
    @Transactional
    public boolean deletePost(Long postId, Long userId) {
        log.info("删除动态: postId={}, userId={}", postId, userId);

        try {
            // 安全删除，确保用户只能删除自己的动态
            int result = postsMapper.deletePostByIdAndUserId(postId, userId);
            boolean success = result > 0;

            if (success) {
                log.info("动态删除成功: postId={}", postId);
            } else {
                log.warn("动态删除失败或无权操作: postId={}, userId={}", postId, userId);
            }

            return success;
        } catch (Exception e) {
            log.error("删除动态失败: postId={}, userId={}", postId, userId, e);
            throw new RuntimeException("删除动态失败");
        }
    }

    public PostVO getPostById(Long postId) {
        log.info("查询动态详情: postId={}", postId);

        try {
            PostVO post = postsMapper.selectPostById(postId);
            if (post == null) {
                log.warn("动态不存在: postId={}", postId);
                throw new RuntimeException("动态不存在");
            }
            log.info("动态查询成功: postId={}", postId);
            return post;
        } catch (Exception e) {
            log.error("查询动态详情失败: postId={}", postId, e);
            throw new RuntimeException("查询动态详情失败");
        }
    }

    /**
     * 查询用户动态数量
     * @param userId 用户ID
     * @return
     */
    public int getPostsCountByUserId(Long userId) {
        log.info("查询用户动态数量: userId={}", userId);

        try {
            int count = postsMapper.selectPostsCountByUserId(userId);
            log.info("用户 {} 的动态数量: {}", userId, count);
            return count;
        } catch (Exception e) {
            log.error("查询用户动态数量失败: userId={}", userId, e);
            throw new RuntimeException("查询动态数量失败");
        }
    }

    /**
     * 查询所有动态数量
     * @return
     */
    public int getAllPostsCount() {
        log.info("查询用户动态数量");

        try {
            int count = postsMapper.selectAllPostsCount();
            log.info("所有动态数量: {}", count);
            return count;
        } catch (Exception e) {
            log.error("查询所有动态数量失败：", e);
            throw new RuntimeException("查询动态数量失败");
        }
    }
}